<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query" label-suffix=" :">
      <el-form-item label="采购编号">
        <el-input v-model.trim="query.purchaseCode" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="采购站点">
        <el-tree-select
          v-model="query.purchaseOrgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props: {
              value: 'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData,
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item :table-form-merge="0.2">
        <el-checkbox v-model="query.checked" style="margin-right: 20px;">包含下级</el-checkbox>
      </el-form-item>
      <el-form-item label="车牌号">
        <el-input v-model.trim="query.licensePlate" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="燃气类型">
        <el-select v-model="query.purchaseType" filterable clearable>
          <el-option
            v-for="(item, index) in purchaseTypeList"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否算运费">
        <el-select v-model="query.iscalculateFreight" filterable clearable placeholder="请选择">
          <el-option :value="1" label="是" />
          <el-option :value="2" label="否" />
        </el-select>
      </el-form-item>
      <el-form-item :table-form-merge="2" label="采购时间" clearable>
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
        />
      </el-form-item>
      <template v-slot:btns>
        <el-button v-permission="1" type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button v-permission="2" type="primary" icon="el-icon-plus" @click="handAdd">新增</el-button>
        <el-button v-permission="5" type="primary" icon="el-icon-download" @click="exportFile">导出</el-button>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="columns"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <add ref="add" :org-list="orgList" />
    <purchase-detail ref="purchaseDetail" />
  </div>
</template>

<script>
  import dayjs from 'dayjs'
  import { purchaseUnloadingList, purchaseUnloadingExport, queryExportDomain, purchaseUnloadingDel } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { mapGetters } from 'vuex'
  import Add from './components/Add'
  import PurchaseDetail from './components/PurchaseDetail'
  export default {
    name: 'purchaseUnload', // 采购卸车
    components: {
      Add,
      PurchaseDetail
    },
    data() {
      return {
        actionColWidth: 80,
        exportDomain: '',
        searchParams: {},
        query: {
          purchaseCode: '',
          orgId: '',
          checked: false,
          iscalculateFreight: '',
          licensePlate: '',
          purchaseType: ''
        },
        date: [],
        tableData: {
          total: 0,
          data: []
        },
        purchaseTypeList: [
          { label: '液化气', value: 1 },
          { label: '丙烷', value: 2 }
        ]
      }
    },
    computed: {
      ...mapGetters([
        'orgList'
      ]),
      columns: function() {
        return [
          {
            type: 'index'
          },
          {
            prop: 'purchaseCode',
            label: '采购编号',
            width: 160,
            render: (h, { row }) => {
              return (
                      <div>
                            <el-link underline={false} size='mini' onClick={() => this.openDetail(row)}>
                                  {row.purchaseCode}
                            </el-link>
                        </div>
                      )
            }
          },
          {
            prop: 'licensePlate',
            width: 120,
            label: '车牌号'
          },
          {
            prop: 'driver',
            width: 100,
            label: '司机'
          },
          {
            prop: 'purchaseType',
            label: '燃气类型',
            width: 100,
            render: (h, { row }) => {
              const str = row.purchaseType === 1 ? '液化气' : '丙烷'
              return <span>{str}</span>
            }
          },
          {
            prop: 'weightBefore',
            width: 150,
            label: '卸车前车辆毛重(kg)'
          },
          {
            prop: 'weightAfter',
            width: 150,
            label: '卸车后车辆毛重(kg)'
          },
          {
            prop: 'totalWeight',
            width: 120,
            label: '实际卸货量(kg)'
          },
          {
            prop: 'unitPrice',
            width: 130,
            label: '出厂单价(kg/元)'
          },
          {
            prop: 'freight',
            width: 120,
            label: '运费(kg/元)'
          },
          {
            prop: 'iscalculateFreight',
            width: 80,
            label: '是否算运费',
            render: (h, { row }) => {
              const str = row.iscalculateFreight === 1 ? '是' : '否'
              return <span>{str}</span>
            }
          },
          {
            prop: 'remark',
            width: 180,
            label: '备注'
          },
          {
            prop: 'purchaseOrgName',
            width: 120,
            label: '采购站点'
          },
          {
            prop: 'purchaseDt',
            label: '采购日期',
            width: 140,
            render: (h, { row }) => (
            <span>
              {row.purchaseDt && dayjs(row.purchaseDt).format('YYYY-MM-DD')}
            </span>
          )
          },
          {
            prop: 'operateName',
            width: 100,
            label: '操作人'
          },
          {
            prop: 'modifyTime',
            width: 160,
            label: '操作时间',
            render: (h, { row }) => (
            <span>
              {row.modifyTime && dayjs(row.modifyTime).format('YYYY-MM-DD HH:mm:ss')}
            </span>
          )
          },
          {
            label: '操作',
            align: 'center',
            fixed: 'right',
            className: 'action-col',
            width: this.actionColWidth,
            render: (h, { row }) => {
              return (
                            <div>
                                <el-link v-permission='4' underline={false} size='mini' onClick={() => this.handEdit(row)}>
                                    编辑
                                </el-link>
                                <el-link v-permission='3' underline={false} size='mini' type='danger' onClick={() => this.handDel(row)}>
                                    删除
                                </el-link>
                            </div>
                        )
            }
          }
        ]
      }
    },
    async created() {
      await Promise.all([this.getTreeData(), this.getExportDomain()])
    },
    methods: {
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain)
          .then((res) => {
            this.exportDomain = res.data
          })
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.query.purchaseOrgSNNo = value.orgSNNo
        this.query.purchaseOrgId = value.orgId
        // this.$nextTick(() => {
        //   this.$refs.lbTable.fetch({ currentPage: 1 })
        // })
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        // if (this.date && this.date.length > 1) {
        //     query[`${this.dateType}`] = parseTime(this.date[0], '{y}-{m}-{d} {h}:{i}:{s}')
        //     query[`${this.dateType}End`] = parseTime(this.date[1], '{y}-{m}-{d} {h}:{i}:{s}')
        // }
        // if (this.qtype && this.txt) {
        //     query[this.qtype] = this.txt
        // }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (this.date && this.date.length > 0) {
          query.purchaseDt = dayjs(this.date[0]).format('YYYY-MM-DD')
          query.purchaseDtEnd = dayjs(this.date[1]).format('YYYY-MM-DD')
        }
        if (query.checked) {
          query.purchaseOrgId = 0
        }
        if (!query.purchaseOrgSNNo) {
          delete query.purchaseOrgId
        }
        delete query.checked
        const res = await purchaseUnloadingList(query)
        this.searchParams = query
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      // 导出
      async exportFile() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(_this.columns))
          copyColumn.pop() // 删除操作列
          const str = {}
          copyColumn.forEach(item => {
            str[item.prop] = item.label
          })
          purchaseUnloadingExport({
            // paramInfo: _this._getQuery(_this.searchParams),
            paramInfo: _this.searchParams,
            kv: str // 表格列
          }).then((res) => {
            window.open(`${_this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach(it => {
                width += (it.offsetWidth + 10)
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      handDel(row) {
        this.$confirm(`确定要删除该记录吗？`, '提示', {
          type: 'warning'
        }).then(() => {
          this.delSubmit(row)
        })
      },
      async delSubmit(row) {
        const params = {
          id: row.id
        }
        const { status } = await purchaseUnloadingDel(params)
        if (status === 200) {
          this.$notify({
            title: '提示',
            message: `删除成功`,
            type: 'success',
            duration: 2000
          })
          this.search()
        }
      },
      async handEdit(row) {
        await this.$refs.add.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      async handAdd() {
        await this.$refs.add.open()
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      async openDetail(row) {
        await this.$refs.purchaseDetail.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      }

    }
  }
</script>

<style lang="scss" scoped></style>
